import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:provider/provider.dart';
import 'package:tiktokadult/assets_tool/images.dart';
import 'package:tiktokadult/hj_utils/widget_utils.dart';

import '../../config/config.dart';
import '../../hj_page/main_page/provider/msg_provider.dart';
import '../../hj_page/mine_business/mine_vip/online_pay_page.dart';
import '../../hj_page/mine_business/mine_vip/vip_card_item.dart';
import '../../hj_page/mine_business/mine_vip/vip_support_model.dart';
import '../../hj_utils/api_service/mine_service.dart';
import '../../tools_base/debug_log.dart';
import '../../tools_base/loading/l_error_widget.dart';
import '../../tools_base/loading/loading_center_widget.dart';
import '../../tools_base/widget/net_image_widget.dart';

class NewerVipAlert extends StatefulWidget {
  const NewerVipAlert({super.key});

  @override
  State<NewerVipAlert> createState() => _NewerVipAlertState();
}

class _NewerVipAlertState extends State<NewerVipAlert> {
  static List<VipProductModel> vipList = [];
  VipProductModel? currentProductModel;
  bool isLoading = true;

  @override
  void initState() {
    super.initState();
    if (vipList.isEmpty) {
      WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
        _loadData();
      });
    } else {
      currentProductModel = vipList.first;
      isLoading = false;
    }
  }

  void _loadData() async {
    try {
      final rawDataModel = await MineService.getVipProductInfo();
      VipProductListModel? vipCardInfo;
      rawDataModel?.list?.forEach((element) {
        if (element.position == '会员卡') {
          vipCardInfo = element;
        }
      });
      if (Config.recommendVipIds?.isNotEmpty == true) {
        vipList.clear();
        for (VipProductModel model in (vipCardInfo?.list ?? [])) {
          for (var vid in Config.recommendVipIds!) {
            if (vid == model.productID) {
              vipList.add(model);
              break;
            }
          }
        }
        if (vipList.isNotEmpty) {
          currentProductModel = vipList.first;
        }
      }
    } catch (e) {
      debugLog(e.toString());
    }
    isLoading = false;
    if (mounted) setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<MineMsgProvider>(
      builder: (context, newser, child) {
        return Material(
          color: Colors.transparent,
          child: InkWell(
            onTap: () {
              if (isLoading) return;
              Get.back();
            },
            child: Container(
              alignment: Alignment.bottomCenter,
              child: GestureDetector(
                onTap: () {},
                child: Container(
                  padding: EdgeInsets.only(top: 16, bottom: 16),
                  decoration: BoxDecoration(
                    color: Color(0xff030F18),
                    borderRadius: BorderRadius.only(
                      topRight: Radius.circular(20),
                      topLeft: Radius.circular(20),
                    ),
                  ),
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Container(
                        width: 36,
                        height: 5,
                        decoration: BoxDecoration(
                          color: Color(0x33FFFFFF),
                          borderRadius: BorderRadius.circular(10),
                        ),
                      ),
                      16.sizeBoxH,
                      Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Text(
                            "特邀会员优惠",
                            style: TextStyle(
                              color: Colors.white,
                              fontSize: 16,
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                          12.sizeBoxW,
                          _buildTimeItem(newser.newerTimeHour),
                          Text(
                            ":",
                            style: TextStyle(color: Colors.white, fontSize: 20),
                          ),
                          _buildTimeItem(newser.newerTimeMin),
                          Text(
                            ":",
                            style: TextStyle(color: Colors.white, fontSize: 20),
                          ),
                          _buildTimeItem(newser.newerTimeSec),
                        ],
                      ),
                      16.sizeBoxH,
                      _buildVipCardInfo(),
                    ],
                  ),
                ),
              ),
            ),
          ),
        );
      },
    );
  }

  Widget _buildVipCardInfo() {
    if (isLoading) {
      return SizedBox(height: 250, child: LoadingCenterWidget());
    } else if (currentProductModel == null) {
      return SizedBox(
        height: 250,
        child: CErrorWidget(
          retryOnTap: () {
            isLoading = true;
            setState(() {});
            _loadData();
          },
        ),
      );
    } else {
      return Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Container(
            height: 60,
            child: ListView.builder(
              padding: EdgeInsets.only(left: 12),
              scrollDirection: Axis.horizontal,
              itemCount: currentProductModel?.newPrivilege?.length ?? 0,
              itemBuilder: (BuildContext context, int index) {
                final privilege = currentProductModel?.newPrivilege![index];
                return Container(
                  width: 60,
                  height: 60,
                  margin: EdgeInsets.only(right: 10),
                  child: VipProductPrivilegeItem(privilege, isShowOnePrivilege: true),
                );
              },
            ),
          ),
          16.sizeBoxH,
          if (vipList.length == 1)
            Container(
              width: Get.width,
              height: 152,
              alignment: Alignment.center,
              child: AspectRatio(
                aspectRatio: 118 / 152,
                child: Container(
                  padding: EdgeInsets.all(1.5),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(12),
                    border: Border.all(color: Color(0xffC99B05)),
                  ),
                  child: InkWell(
                    onTap: () {
                    },
                    child: Stack(
                      fit: StackFit.expand,
                      children: [
                        NetworkImageLoader(
                          imageUrl: vipList.first.newBgImg,
                          borderRadius: 12,
                        ),
                        Positioned(
                          top: 6,
                          right: 6,
                          child: Image.asset(
                            "mine_withdraw_sel.png".mineImgPath,
                            width: 24,
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            )
          else
            GridView.builder(
              padding: EdgeInsets.symmetric(horizontal: 42),
              itemCount: vipList.length,
              shrinkWrap: true,
              physics: NeverScrollableScrollPhysics(),
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 2, //横向数量
                crossAxisSpacing: 18, //间距
                mainAxisSpacing: 8, //行距
                childAspectRatio: 118 / 152,
              ),
              itemBuilder: (ctx, index) {
                bool isSelected = currentProductModel?.productID == vipList[index].productID;
                return Container(
                  padding: EdgeInsets.all(1.5),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(12),
                    border: Border.all(color: Color(0xffC99B05)),
                  ),
                  child: InkWell(
                    onTap: () {
                      currentProductModel = vipList[index];
                      setState(() {});
                    },
                    child: Stack(
                      fit: StackFit.expand,
                      children: [
                        NetworkImageLoader(
                          imageUrl: vipList[index].newBgImg,
                          borderRadius: 12,
                        ),
                        Positioned(
                          top: 6,
                          right: 6,
                          child: Image.asset(
                            isSelected ? "mine_withdraw_sel.png".mineImgPath : 'selected_no.webp'.videoPath,
                            width: 24,
                          ),
                        ),
                      ],
                    ),
                  ),
                );
              },
            ),
          12.sizeBoxH,
          Container(
            margin: EdgeInsets.symmetric(horizontal: 12),
            padding: EdgeInsets.symmetric(horizontal: 12, vertical: 12),
            decoration: BoxDecoration(
              color: Color(0x0DFFFFFF),
              borderRadius: BorderRadius.circular(12),
            ),
            child: Column(
              children: [
                _buildTitleCount(
                  "原价",
                  "¥${currentProductModel?.originalPriceUI}",
                  style: TextStyle(
                    color: Color(0x8CFFFFFF),
                    fontSize: 14,
                    decoration: TextDecoration.lineThrough,
                    decorationColor: Color(0x8CFFFFFF),
                  ),
                ),
                16.sizeBoxH,
                _buildTitleCount(
                  "限时价格",
                  "¥${currentProductModel?.discountedPriceUI}",
                  style: TextStyle(
                    color: Color(0xFFFF9000),
                    fontSize: 14,
                  ),
                ),
                16.sizeBoxH,
                _buildTitleCount(
                  "优惠价格",
                  "¥${currentProductModel!.originalPriceUI - currentProductModel!.discountedPriceUI}",
                ),
                16.sizeBoxH,
                Container(height: 1, color: Colors.white.withOpacity(0.05)),
                16.sizeBoxH,
                _buildTitleCount(
                  "总计",
                  "¥${currentProductModel?.discountedPriceUI}",
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 14,
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ],
            ),
          ),
          18.sizeBoxH,
          GestureDetector(
            onTap: () {
              Get.bottomSheet(
                OnlinePayPage(vipProductModel: currentProductModel),
                isScrollControlled: true,
              );
            },
            child: Container(
              alignment: Alignment.center,
              height: 44,
              margin: EdgeInsets.symmetric(horizontal: 12),
              decoration: BoxDecoration(
                color: Color(0xffE1351F),
                borderRadius: BorderRadius.circular(4),
              ),
              child: Text(
                "立即支付",
                style: textStyle(16, Colors.white, FontWeight.w500),
              ),
            ),
          )
        ],
      );
    }
  }

  Widget _buildTitleCount(String title, String count, {TextStyle? style}) {
    return Row(
      children: [
        Text(
          title,
          style: textStyle(14, Color(0xE5FFFFFF), FontWeight.w400),
        ),
        Spacer(),
        Text(
          count,
          style: style ??
              TextStyle(
                color: Color(0x8CFFFFFF),
                fontSize: 14,
              ),
        ),
      ],
    );
  }

  Widget _buildTimeItem(String? count) {
    return Container(
      width: 24,
      height: 24,
      alignment: Alignment.center,
      decoration: BoxDecoration(
        color: Color(0xffE1351F),
        borderRadius: BorderRadius.circular(3),
      ),
      child: Text(
        count ?? "00",
        style: TextStyle(
          color: Colors.white,
          fontSize: 14,
          fontWeight: FontWeight.w500,
        ),
      ),
    );
  }
}
